﻿using System;
using System.Data.Services;
using System.Linq;
using System.Linq.Expressions;

namespace AstoriaPlus
{
	public interface IEntityQueryRules<TDataService, TDataSource, TEntity> : IFluentInterface
		where TDataService : DataService<TDataSource>
		where TDataSource : class
		where TEntity : class
	{
		QueryExpression<TEntity, DataServiceQueryContext<TDataService, TDataSource>> Where(Expression<Func<TEntity, bool>> predicate);

		QueryExpression<TEntity, DataServiceQueryContext<TDataService, TDataSource>> Where(Expression<Func<TEntity, DataServiceQueryContext<TDataService, TDataSource>, bool>> predicate);
	}

	public class EntityQueryRules<TDataService, TDataSource, TEntity> : IEntityQueryRules<TDataService, TDataSource, TEntity>
		where TDataService : DataService<TDataSource> 
		where TDataSource : class
		where TEntity : class
	{
		private readonly ExtendedDataServiceConfiguration<TDataService, TDataSource> configuration;
		private readonly string entitySetName;

		public EntityQueryRules(ExtendedDataServiceConfiguration<TDataService, TDataSource> configuration, string entitySetName)
		{
			this.configuration = configuration;
			this.entitySetName = entitySetName;
		}

		public QueryExpression<TEntity, DataServiceQueryContext<TDataService, TDataSource>> Where(Expression<Func<TEntity, bool>> predicate)
		{
			ParameterExpression param = Expression.Parameter(typeof(DataServiceQueryContext<TDataService, TDataSource>), "c");
			var lambda = Expression.Lambda<Func<TEntity, DataServiceQueryContext<TDataService, TDataSource>, bool>>(
				predicate.Body, predicate.Parameters.First(), param);

			return lambda;
		}

		public QueryExpression<TEntity, DataServiceQueryContext<TDataService, TDataSource>> Where(Expression<Func<TEntity, DataServiceQueryContext<TDataService, TDataSource>, bool>> predicate)
		{
			return predicate;
		}
	}
}
